<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="/static/layui/css/layui.css" rel="stylesheet">
  <style>
    .flow-div .flow-div-media {
      display: grid;
      gap: 5px;
      grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    }

    .flow-div .flow-div-media li img {
      width: 100%;
      height: 150px;
      object-fit: cover;
    }

    .showVideo {
      position: relative;
    }

    .play-btn {
      cursor: pointer;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 50px;
      height: 50px;
      background: rgba(0, 0, 0, 0.5);
      border: none;
      border-radius: 50%;
      color: white;
      font-size: 20px;
    }

    .play-btn:hover {
      background: rgba(0, 0, 0, 0.7);
    }

    .flow-div video {
      display: block;
      width: 100%;
      opacity: 1;
      height: 150px;
      object-fit: cover;
      filter: saturate(150%);
      background-color: black;
    }

    .flow-div .flow-div-other {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 1%;
    }

    .flow-div .showOther {
      clear: both;
      margin: 0;
      font-size: 14px;
      width: 100%;
      height: 50px;
      line-height: 50px;
      text-align: left;
      overflow: hidden;
    }

    .layui-layer-transparent {
      background: transparent !important;
      box-shadow: none !important;
    }
    .last-row-container {
      width: 100%;
    }
  </style>
</head>

<body>
  <div class="flow-div" id="ID-flow-div-manual">
    <div class="flow-div-media">
      {if $data['img']}
      {foreach $data['img'] as $key => $value}
      <li><a href="javascript:;"><img data-index="{$key}" onclick="showMessageImg(this)" src="{$value['mediaUrl']}"></a></li>
      {/foreach}
      {/if}
      {if $data['video']}
      {foreach $data['video'] as $key => $value}
      <li class="showVideo">
        <!-- 移除 controls 属性以去掉播放控制 -->
        <video 
          onclick="return false;" 
          src="{$value['mediaUrl']}" 
          name="media"
        >
          <source src="{$value['mediaUrl']}" type="video/mp4">
        </video>
        <!-- 添加播放按钮 -->
        <button class="play-btn" id="iframe-{$value['id']}" onclick="showVideoPopup(this)" data-src="{$value['mediaUrl']}">▶</button>
      </li>
      {/foreach}
      {/if}
    </div>

    {if $data['text']}
    <div class="flow-div-other">
      {foreach $data['text'] as $key => $value}
      <li class="showOther">
        <span><a href="javascript:;" data-title="{$value['file_name']}"
            data-url="/tools/reader?material_relation_id={$value['id']}" onclick="showTextPopup(this)">点击阅读
            {$value['file_name']}</a></span>
      </li>
      {/foreach}
    </div>
    {/if}
    {if $data['other']}
    <div class="flow-div-other">
      {foreach $data['other'] as $key => $value}
      <li class="showOther">
        <span>
          <!-- 修改为点击事件触发下载 -->
          <a href="javascript:;" onclick="downloadFile('{$value['mediaUrl']}', '{$value['file_name']}')">点击下载 {$value['file_name']}</a>
        </span>
      </li>
      {/foreach}
    </div>
    {/if}
  </div>

  <input type="hidden" value="{$id}" id="previewId">
  <input type="hidden" value="{$isMobile}" id="isMobile">

  <!-- 请勿在项目正式环境中引用该 layui.js 地址 -->
  <script src="/static/layui/layui.js"></script>
  <script>
    var $ = layui.$;

    // 动态调整媒体布局
    // function adjustLayout() {
    //   const mediaContainer = $('.flow-div-media');
    //   const mediaCount = mediaContainer.find('li').length;

    //   if (mediaCount > 0) {
    //     let mediaColumns;
    //     if (mediaCount <= 3) {
    //       // 当总数小于等于 3 个时，每个元素最大 300px
    //       mediaColumns = `repeat(auto-fill, minmax(150px, 1fr))`;
    //     } else {
    //       const remainder = mediaCount % 3;
    //       if (remainder === 0) {
    //         // 能被 3 整除，每行显示 3 个
    //         mediaColumns = 'repeat(3, 1fr)';
    //       } else {
    //         // 不能被 3 整除，前面行每行 3 个，最后一行用最大宽度限制
    //         mediaColumns = `repeat(3, 1fr) repeat(auto-fill, minmax(150px, 200px))`;
    //       }
    //     }
    //     mediaContainer.css('grid-template-columns', mediaColumns);
    //   }
    // }

    // adjustLayout();

    function showMessageImg(obj) {
      var imgList = $('.flow-div-media li img').map(function () {
        return $(this).attr('src');
      }).get();
      var imgArray = [];
      for (var i = 0; i < imgList.length; i++) {
        imgArray.push({
          "alt": "",
          "pid": i, // 图片id
          "src": imgList[i], // 原图地址
          "thumb": "" // 缩略图地址
        })
      }
      // console.log(imgArray)
      // var imgUrl = $(obj).attr('src');
      var json = {
        "title": "", // 相册标题
        "id": 0, // 相册id
        "start": $(obj).attr('data-index'), // 初始显示的图片序号，默认0
        "data": imgArray
      }

      if (parent.layer) {
        var layer = parent.layer
      }

      layer.photos({
        photos: json,
        anim: 5
      });

    }

    function showVideoPopup(obj) {
      var videoUrl = $(obj).attr('data-src');
      // 修改视频标签样式，让高度达到 100% 并保持比例
      // 调整视频样式，让视频根据高度缩放并居中
      // var videoHtml = '<video autoplay controls name="media" style="max-height: 90vh; max-width: 90vw; margin: auto; display: block;"><source src="' + videoUrl + '" type="video/mp4"></video>';
      // 保持容器样式不变，限制最大和最小宽高，并添加居中样式
      // var centerDiv = '<div style="display: flex; justify-content: center; align-items: center; height: 100vh;">' + videoHtml + '</div>';
  
      if (parent.layer) {
        var layer = parent.layer
        parent.stopOther(obj)
      }

      var isMobile = $("#isMobile").val()
      if (isMobile) {
        var area = ['100%', '100%']
        var closeBtn = 1
        var anim = 0
        var title='视频播放'
        var skin = ''
        var seccessCss={}
      } else {
        var area = ['50%', '80%']
        var closeBtn = 0
        var anim = 2
        var title=false
        var skin = 'layui-layer-transparent'
        var seccessCss={
            'background-color': 'transparent',
        }
      }

      layer.open({
          type: 2,
          title: title,
          closeBtn: closeBtn,
          shade: 1,
          // 优化弹层按钮样式
          // btnStyle: ['background-color: #007BFF; color: white; border: none; border-radius: 4px;'],
          area: area,
          // 修改为透明背景
          skin: skin, 
          shadeClose: true,
          content: videoUrl,
          // 添加动画效果
          anim: anim, 
          success: function(layero, index) {
            // 弹层打开后添加过渡效果
            if (seccessCss) {
              layero.css(seccessCss)
            }
            // layero.css({
            //   // 'opacity': 0,
            //   // 'transform': 'scale(0.8)',
            //   // 'box-show': 'none !important',
            //   'background-color': 'transparent',
            // })
            // .animate({
            //   'opacity': 1,
            //   'transform': 'scale(1)'
            // }, 300);
          },
          // end: function() {
            // 弹层关闭时添加过渡效果
            // $('.layui-layer').animate({
            //   'opacity': 0,
            //   'transform': 'scale(0.8)',
            //   'box-show': 'none'
            // }, 300);
          // }
      });
    }

    function showTextPopup(obj) {

      if (parent.layer) {
        var layer = parent.layer
      }

      layer.open({
        type: 1,
        title: $(obj).attr('data-title'),
        shade: 0.8,
        closeBtn: 1,
        shadeClose: false,
        area: ['100%', '100%'],
        resize: false,
        maxmin: false,
        // moveOut: true,
        scrollbar: true,
        content: '<iframe sandbox="allow-same-origin allow-scripts allow-popups" src="' + $(obj).attr('data-url') + '" allowfullscreen="true" allowtransparency="true" width="100%" height="100%" frameborder="0" scrolling="yes"></iframe>'
      });
    }

    // 检查父窗口和 jQuery 是否可用
    if (parent && parent.$) {
      // 本页面onload结束后执行下面的代码
      window.onload = function () {
        var flowDivHeight = Math.max($('html').height(), $('body').height()) + 15;
        var id = $('#previewId').val();
        console.log('#iframe-sourcematerial-' + id);
        console.log(flowDivHeight)
        // 设置父窗口中指定 id 的 iframe 的高度
        parent.$('#iframe-sourcematerial-' + id).height(flowDivHeight);
        // 父集的overflow hidden
        // parent.$('#iframe-sourcematerial-' + id).parent().css('overflow', 'hidden');
      }
    }

    // 添加下载函数
    function downloadFile(url, fileName) {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';

        // 显示加载提示
        let layer;
        if (parent.layer) {
            layer = parent.layer;
        } else {
            layer = layui.layer;
        }
        const loadingIndex = layer.load(1, {
            shade: [0.1, '#fff']
        });

        xhr.onload = function() {
            // 关闭加载提示
            layer.close(loadingIndex);
            if (xhr.status === 200) {
                const blob = new Blob([xhr.response]);
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = fileName;
                link.style.display = 'none';

                if (window.self !== window.top) {
                    window.parent.document.body.appendChild(link);
                } else {
                    document.body.appendChild(link);
                }

                link.click();

                if (window.self !== window.top) {
                    window.parent.document.body.removeChild(link);
                } else {
                    document.body.removeChild(link);
                }

                // 释放 URL 对象
                URL.revokeObjectURL(link.href);
            } else {
                // 下载失败提示
                layer.msg('下载失败，请稍后重试', { icon: 5 });
            }
        };

        xhr.onerror = function() {
            // 关闭加载提示
            layer.close(loadingIndex);
            // 网络错误提示
            layer.msg('网络错误，请检查网络连接', { icon: 5 });
        };

        xhr.send();
    }
  </script>

</body>

</html>